#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from config import etc
from utils import log
from utils.session_base import ApiHost, ApiGuest
from utils.session_mc import BaseHandler
from controls import data_shout_mysql


class ShoutListHandler(BaseHandler):
    @ApiGuest
    def post(self):
        userid = self.ss_params.get('userid')
        if not userid:
            log.w('params fetching error')
            res = {'idx': self.ss_idx, 'ret': 1, 'msg': etc.err_500, 'res': {}}
            self.write(json.dumps(res))
            self.finish()
            return

        result = data_shout_mysql.get_shout_by_userid(userid)
        if result:
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': result}
        else:
            res = {'idx': self.ss_idx, 'ret': 0, 'msg': 'ok', 'res': {}}
        self.write(json.dumps(res))
        self.finish()
        return


class ShoutUpdateHandler(BaseHandler):
    @ApiHost
    def post(self):
        userid = self.ss_user['userid']
        content1 = self.ss_params.get('content1', '')
        content2 = self.ss_params.get('content2', '')
        content3 = self.ss_params.get('content3', '')

        if data_shout_mysql.get_shout_by_userid(userid):
            if not data_shout_mysql.update_shout_by_userid(userid, {
                'content1': content1,
                'content2': content2,
                'content3': content3,
            }):
                self._generate_res(1, 'update error', 'update_shout')
                return
        else:
            if not data_shout_mysql.add_shout_item({
                'userid': userid,
                'content1': content1,
                'content2': content2,
                'content3': content3,
            }):
                self._generate_res(1, 'add error', 'add_shout')
                return

        ret = {'idx': self.ss_idx, 'ret': 0, 'res': {}, 'msg': 'ok'}
        self.write(json.dumps(ret))
        self.finish()
        return

